from fastapi import APIRouter, Form, File, UploadFile, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
import uuid
from ..database import get_db
from ..models import User, Role, UserRelation
from ..schemas import User as UserSchema, UserCreate, UserUpdate, UserRelationCreate
from ..auth import get_current_active_user
from ..utils.files import save_icon_to_local
from ..utils.security import get_password_hash

router = APIRouter(prefix="/api/chance/users", tags=["users"])

# 获取用户列表
@router.get("/", response_model=List[UserSchema])
async def get_users(
    skip: int = 0,
    limit: int = 20,
    username: str = None, # 用户ID名
    name: str = None, # 用户姓名
    db: Session = Depends(get_db)
):
    # 构建查询
    query = db.query(User)
    
    # 添加过滤条件
    if username:
        query = query.filter(User.username.contains(username))
    if name:
        query = query.filter(User.name.contains(name))
    
    # 执行查询并应用分页
    users = query.offset(skip).limit(limit).all()
    return users

# 获取当前登录用户信息
@router.get("/me", response_model=UserSchema)
async def get_user(
    current_user: User = Depends(get_current_active_user)
):
    return current_user

# 获取单个用户
@router.get("/{user_id}", response_model=UserSchema)
async def get_user(
    user_id: int,
    db: Session = Depends(get_db),
):
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=500, detail="用户不存在")
    return user

# 创建用户
@router.post("/", response_model=UserSchema)
async def create_user(
    username: str = Form(...),
    password: str = Form(...),
    name: str = Form(...),
    phone: str = Form(...),
    category: str = Form(...),
    sec_type: int = Form(0),
    desc: str = Form(""),
    student_phone: str = Form(None),
    icon: UploadFile = File(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 检查用户名是否已存在
    db_user = db.query(User).filter(User.username == username).first()
    if db_user:
        raise HTTPException(status_code=500, detail="用户名已存在")
    
    # 保存图标（如果有）
    icon_path = None
    if icon:
        icon_id = str(uuid.uuid4())
        icon_path = save_icon_to_local(icon, icon_id)

    # 创建新用户
    db_user = User(
        username=username,
        password=get_password_hash(password),
        name=name,
        phone=phone,
        category=category,
        sec_type=sec_type if category == "3" else 0,  # 只有老师类型才设置二级权限
        desc=desc if category == "3" else "",  # 只有老师类型才设置简介
        icon_path=icon_path,
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    # 如果是家长用户且提供了学生手机号，则创建关联
    if category == "2" and student_phone:
        # 检查是否已存在关联
        existing_relation = db.query(UserRelation).filter(
            UserRelation.parent_phone == phone
        ).first()
        
        if not existing_relation:
            # 创建新的关联
            user_relation = UserRelation(
                parent_phone=phone,
                student_phone=student_phone
            )
            db.add(user_relation)
            db.commit()
    
    return db_user

# 更新用户
@router.put("/{user_id}", response_model=UserSchema)
async def update_user(
    user_id: int,
    name: str = Form(...),
    password: str = Form(...),
    phone: str = Form(...),
    category: str = Form(...),
    sec_type: int = Form(0),
    desc: str = Form(""),
    student_phone: str = Form(None),
    icon: UploadFile = File(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 查找用户
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=500, detail="用户不存在")
    
    # 更新用户基本信息
    update_data = {}
    if name is not None:
        update_data['name'] = name
    if password is not None:
        update_data['password'] = get_password_hash(password)
    if phone is not None:
        update_data['phone'] = phone
    if category is not None:
        update_data['category'] = category
        # 只有老师类型才设置二级权限，其他类型重置为0
        update_data['sec_type'] = sec_type if category == "3" else 0
        # 只有老师类型才设置简介，其他类型重置为空
        update_data['desc'] = desc if category == "3" else ""

    # 更新图标（如果有）
    if icon:
        icon_id = str(uuid.uuid4())
        icon_path = save_icon_to_local(icon, icon_id)
        update_data['icon_path'] = icon_path
    
    # 更新其他字段
    for key, value in update_data.items():
        setattr(db_user, key, value)
    
    # 处理家长与学生的关联关系
    if category == "2":
        # 检查是否已存在关联
        existing_relation = db.query(UserRelation).filter(
            UserRelation.parent_phone == db_user.phone
        ).first()
        
        if student_phone:
            # 如果提供了学生手机号，则创建或更新关联
            if existing_relation:
                existing_relation.student_phone = student_phone
            else:
                user_relation = UserRelation(
                    parent_phone=db_user.phone,
                    student_phone=student_phone
                )
                db.add(user_relation)
    
    db.commit()
    db.refresh(db_user)
    return db_user

# 注销用户
@router.post("/deactivate/{user_id}", response_model=UserSchema)
async def deactivate_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=500, detail="用户不存在")
    setattr(db_user, "is_active", False)
    db.commit()
    db.refresh(db_user)
    return db_user
# 恢复用户
@router.post("/reactivate/{user_id}", response_model=UserSchema)
async def reactivate_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=500, detail="用户不存在")
    setattr(db_user, "is_active", True)
    db.commit()
    db.refresh(db_user)
    return db_user